package de.fme.urlshortener;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.alfresco.repo.urlshortening.BitlyUrlShortenerImpl;

/**
 * @author PloetzJ
 * 
 * added "collectClicks()" function.
 * This function calls bitly and parses the number of clicks out of a JSON http response.
 */

public class FmeBitlyUrlShortenerImpl extends BitlyUrlShortenerImpl
{
    private static final Log log = LogFactory.getLog(FmeBitlyUrlShortenerImpl.class);

    //to be globally set in your "alfresco-global.properties"
    private String username = "o_58amgm89k5";
    private String apiKey = "R_b79a909f6cee18710550b50b8e6e85f2";
    private HttpClient httpClient;

    public FmeBitlyUrlShortenerImpl()
    {
        super();
    }

    @Override
    public String shortenUrl(String longUrl)
    {
        String shortUrl = super.shortenUrl(longUrl);
//        int clicks = this.collectClicks(shortUrl);
        return shortUrl;
    }

    public int collectClicks(String shortUrl)
    {
        if (log.isDebugEnabled())
        {
            log.debug("Collecting Clicks for URL: " + shortUrl);
        }
        // Connect via HTTP get request
    	GetMethod getMethod = new GetMethod();
        getMethod.setPath("/v3/clicks");
        int clicks = -1;
        
        List<NameValuePair> args = new ArrayList<NameValuePair>();
        args.add(new NameValuePair("login", username));
        args.add(new NameValuePair("apiKey", apiKey));
        args.add(new NameValuePair("shortUrl", shortUrl));
        args.add(new NameValuePair("format", "json"));
        getMethod.setQueryString(args.toArray(new NameValuePair[args.size()]));

        try
        {
            int resultCode = httpClient.executeMethod(getMethod);
            if (resultCode == 200)
            {
                String responseBody = getMethod.getResponseBodyAsString();
            	System.out.println("Response Body: " + responseBody);
            	JSONObject json = new JSONObject(responseBody);
            	JSONObject data = json.getJSONObject("data");
            	JSONArray clicksArray = data.getJSONArray("clicks");
            	JSONObject clickObject = (JSONObject) clicksArray.get(0);
            	clicks = clickObject.optInt("user_clicks");
            	System.out.println(clicks);
            	log.info("URL " + shortUrl + " has " + clicks + " clicks.");
            	log.info("HttpResponse was " + responseBody);
            	}
            else
            {
                log.warn("Failed to collect clicks for " + shortUrl + "  - response code == " + resultCode);
                log.warn(getMethod.getResponseBodyAsString());
            }
        }
        catch (Exception ex)
        {
            log.error("Failed to collect clicks for " + shortUrl, ex);
        }
        if (log.isDebugEnabled())
        {
            log.debug("URL " + shortUrl + " has been clicked on " + shortUrl);
        }
        return clicks;
    }
    
    /**
     * @param username the username to set
     */
    public void setUsername(String username)
    {
        this.username = username;
    }
    
    /**
     * @param apiKey the apiKey to set
     */
    public void setApiKey(String apiKey)
    {
        this.apiKey = apiKey;
    }
}